#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/1/17 10:35
# @Author  : maxinehehe
# @Site    : 
# @File    : email_send.py
# @Software: PyCharm
from random import Random
from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_FROM


# 产生随机码
def send_register_email(email, send_type='register'):
    #  type 是注册 还是找回密码发送的
    # model： EmailVerifyRecord
    # 先保存至数据库 供之后查询使用
    email_record = EmailVerifyRecord()  # 实例化模型对象
    if send_type == "update_email":
        code = random_str(4) # code随机字符串
    else:
        code = random_str(16) # code随机字符串
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    # print  '---',email_record
    email_record.save() # 保存
    # 发送邮件 使用自带
    # 先设置发送邮件内容
    email_title = ""
    email_body = ""
    if send_type == 'register':
        email_title = "微慕课在线网注册激活链接"
        email_body = "请点击下方链接激活您的账号：http://127.0.0.1:8000/active/{0}".format(code)
        # 之后进行处理激活链接
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            # 发送成功
            pass
    elif send_type == "forget":
        email_title = "微慕课在线网密码重置链接"
        email_body = "请点击下方链接重置您的密码：http://127.0.0.1:8000/reset/{0}".format(code)   # 需要为此写url分发器
        # 开始发送
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            # 发送成功
            pass
    elif send_type == "update_email":
        email_title = "微慕课在线网邮箱修改验证码"
        email_body = "你的邮箱验证码为：{0}".format(code)   # 需要为此写url分发器
        # 开始发送
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # 在users\views.py进行回调
        if send_status:
            # 发送成功
            pass

def random_str(randomlength=8):
    # 拿到长度随机在其【chars】中取
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


